package cn.sanli.manage.security;

import cn.sanli.manage.mapper.data1.UserMapper;
import cn.sanli.manage.pojo.dto.Login.LoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    public UserMapper userMapper;

   @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LoginDTO loginDTO = userMapper.selectUserMapper(s);
       System.out.println("loginDto的值为"+loginDTO);
       //用户状态
       boolean status=false;
       if(loginDTO.getStatus()==1){
           status=true;
       }
       //用户有没有被锁定
       boolean isLock=false;
       if(loginDTO.getIsLock()==1){
           isLock=true;
       }
        if (loginDTO != null) {
            //权限处理
            Collection<GrantedAuthority> authories = new ArrayList<>();
            //查询用户角色
            List<Integer> integers = userMapper.selectRoles(s);
            for (Integer role : integers) {
                String s1 = role.toString();
                GrantedAuthority authority = new SimpleGrantedAuthority(s1);
                authories.add(authority);
            }
//            UserDetails userDetail = User.builder()
//                    .username(s)
//                    .password(loginDTO.getCryptograph())
//                    .disabled(loginDTO.getStatus()==2)//faslse【disabled：禁用】
//                    .accountLocked(loginDTO.getIsLock()==2)
//                    .authorities(authories)//权限
//                    .build();
            //UserDetail继承User类，就不会是disabled，而是enable属性【enable】中文含义是启用
            UserDetail userDetail=new UserDetail(loginDTO.getUserName(),loginDTO.getRoleId(), loginDTO.getCenterId(), loginDTO.getDeptId(),loginDTO.getNum(),loginDTO.getCryptograph(),status,isLock,authories);
            return userDetail;
        }
        throw new UsernameNotFoundException("登录用户不存在，请重新操作");
    }

}
